﻿progressApps.controller("progressCtrls",
	function($scope, $http) {

        $('#id-input-file-1').ace_file_input({
            no_file:'工程文件 ...',
            btn_choose:'选择',
            btn_change:'重选',
            droppable:false,
            onchange:null,
            thumbnail:false //| true | large
            //whitelist:'gif|png|jpg|jpeg'
            //blacklist:'exe|php'
            //onchange:''
            //
        });

        $('#id-input-file-2').ace_file_input({
            no_file:'参数文件 ...',
            btn_choose:'选择',
            btn_change:'重选',
            droppable:false,
            onchange:null,
            thumbnail:false //| true | large
            //whitelist:'gif|png|jpg|jpeg'
            //blacklist:'exe|php'
            //onchange:''
            //
        });

        $('#id-input-file-3').ace_file_input({
            no_file:'配置文件 ...',
            btn_choose:'选择',
            btn_change:'重选',
            droppable:false,
            onchange:null,
            thumbnail:false //| true | large
            //whitelist:'gif|png|jpg|jpeg'
            //blacklist:'exe|php'
            //onchange:''
            //
        });

        function findProgressControl() {
        			 $http.get('/progressUIJson')
        			        .success(function (data) {
        			        	$scope.progressControl = eval(data);
        			        });
        		}

        function findCompletePrecess() {
        			 $http.get('/completeUIJson')
        			        .success(function (data) {
        			        	$scope.completeProgresses = eval(data);
        			        });
        		}

        $scope.previewClick = function regionSelect(obj) {
                    $("#preview").trigger("click");
                }

        findProgressControl();
        findCompletePrecess();

        $scope.deleteComplete = function deleteComplete(obj){
                        if(obj==null){
                            alert("找不到obj");
                        }
                        if(obj.progressControl==null){
                            alert("参数不存在");
                        }
                        console.log("obj.id:" + obj.progressControlc.id);
                        var parameter = {"id":obj.progressControlc.id};
                        console.log("parameter:" + parameter);
                        $.ajax({
                            url: '/completeJson',
                            type: 'POST',
                            data: parameter,
                            success:function(data){
                                if(data=="success")
                                {
                                    alert("删除成功!");
                                    findProgressControl();
                                    findCompletePrecess();
                                }
                                else
                                {
                                    alert("接收错误!  " + data);
                                }
                            },
                            error:function(data){
                                alert("系统异常! " + data );
                            }
                        });


                     }
	});


     var msg = null;
     var paragraph = 1024*1024;  //每次分片传输文件的大小 1M
     var blob = null;//  分片数据的载体Blob对象
     var fileList = null; //传输的文件
     var uploadState = 0;  // 0: 无上传/取消， 1： 上传中， 2： 暂停

     //初始化消息框
     function init(){
         msg = document.getElementById("msg");
     }

     /**
      * 选择文件之后触发事件
      */
     function fileSelected_test(){
         fileList = document.getElementById("id-input-file-1");
              var length = fileList.files.length;
           // var frame = document.getElementById('fileFrame');
              for(var i = 0 ; i < fileList.files.length; i++){
                   file = fileList.files[i];
                   if(file){
                        var fileSize = 0;
                        if (file.size > 1024 * 1024)
                             fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                        else
                             fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
     //                           var nameDiv = document.createElement("div");
     //                                nameDiv.setAttribute("id","fileName"+i);
     //                                nameDiv.innerHTML='Name: ' + file.name;
     //                            var sizeDiv = document.createElement("div");
     //                                sizeDiv.setAttribute("id","fileSize"+i);
     //                                sizeDiv.innerHTML='fileSize: ' + fileSize;
     //                            var typeDiv = document.createElement("div");
     //                                typeDiv.setAttribute("id","progressNumber"+i);
     //                                typeDiv.innerHTML='';
                  }
       //                      frame.appendChild(nameDiv);
        //                     frame.appendChild(sizeDiv);
        //                     frame.appendChild(typeDiv);
            }
     }


     /**
      * 分片上传文件
     */
     function uploadFile(file,startSize,endSize,i) {
         var date = file.lastModifiedDate;
         var lastModifyTime = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"-"
          +date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds()
         var reader = new FileReader();
         reader.onload = function loaded(evt) {
         // 构造 xmlHttpRequest 对象，发送文件 Binary 数据
            var xhr = new XMLHttpRequest();
            xhr.sendAsBinary = function(text){
                var data = new ArrayBuffer(text.length);
                var ui8a = new Uint8Array(data, 0);
                for (var i = 0; i < text.length; i++){
                    ui8a[i] = (text.charCodeAt(i) & 255);
                }
                this.send(ui8a);
            }
            xhr.onreadystatechange = function(){
                if(xhr.readyState==4){
                    //表示服务器的相应代码是200；正确返回了数据
                    if(xhr.status==200){
                    //纯文本数据的接受方法
                        var message=xhr.responseText;
                        message = Number(message);
                        uploadProgress(file,startSize,message,i);
                    } else{
                        msg.innerHTML = "上传出错，服务器相应错误！";
                    }
                }
            };//创建回调方法
            xhr.open("POST","appendUpload2Server.do?fileName=" + encodeURIComponent(file.name)+"&fileSize="+file.size+"&lastModifyTime="+lastModifyTime,false);
            xhr.overrideMimeType("application/octet-stream;charset=utf-8");
            xhr.sendAsBinary(evt.target.result);
        };
        if(endSize < file.size){
         //处理文件发送（字节）
            startSize = endSize;
            if(paragraph > (file.size - endSize)){
                endSize = file.size;
            }else{
                endSize += paragraph ;
            }
            if (file.webkitSlice) {
                //webkit浏览器
                blob = file.webkitSlice(startSize, endSize);
            }else
                blob = file.slice(startSize, endSize);
                reader.readAsBinaryString(blob);
         }else{
             document.getElementById('progressNumber').attributes['data-percent'].nodeValue = '上传完成 ' + '100%';
             document.getElementById('progressNumber1').style.width = "100%";
//             setTimeout("alert('文件上传成功！')",500);
             alert("文件上传成功！");
             window.location.reload();
         }
     }


     function uploadFiles(){
         //将上传状态设置成1
         uploadState = 1;
         if(fileList.files.length>0){
             console.log(fileList.files.length);
                for(var i = 0; i < fileList.files.length; i++){
                     var file = fileList.files[i];
                     uploadFileInit(file,i);
                 }
             }else{
                 msg.innerHTML = "请选择上传文件！";
             }
         }
     /**
      * 获取服务器文件大小，开始续传
      * @param file
      * @param i
      */
     function uploadFileInit(file,i){
          if(file){
               var startSize = 0;
               var endSize = 0;
               var date = file.lastModifiedDate;
               var lastModifyTime = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"-"
               +date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds();
               //获取当前文件已经上传大小
               jQuery.post("getChunkedFileSize.do",{"fileName":encodeURIComponent(file.name),"fileSize":file.size,"lastModifyTime":lastModifyTime,"chunkedFileSize":"chunkedFileSize"},
                                   function(data){
                                       if(data != -1){
                                           endSize = Number(data);
                                       }
                                       uploadFile(file,startSize,endSize,i);

                           });
          }
     }

     //显示处理进程
     function uploadProgress(file,startSize,uploadLen,i) {
          var percentComplete = Math.round(uploadLen * 100 / file.size);
          //   console.log(percentComplete.toString());

          document.getElementById('progressNumber1').style.width = percentComplete + "%";
          document.getElementById('progressNumber').attributes['data-percent'].nodeValue = '正在上传 ' + percentComplete.toString() + '%';
          $("#progressbar").show();
          //续传
          if(uploadState == 1){
              uploadFile(file,startSize,uploadLen,i);
          }
     }

     /*
     暂停上传
     */
     function pauseUpload(){
         uploadState = 2;
     }



     function message(){
         var se=confirm("该文件已存在，是否覆盖？");
         if (se==true){
             var _url = '/saveFileToServer';
             var formData = new FormData($('#saveFileToServer')[0]);
             $.ajax({
                    url: _url,
                    type:'POST',
                    data:formData,
                    async:false,
                    cache:false,
                    contentType:false,
                    processData:false,
                    success:function(data){
                        if(data == "文件上传成功"){
                            uploadFiles();
                       //     alert("文件上传成功！");
                       //     window.location.reload();
                        }
                    },
                    error:function(data){
                        alert(data);
                        window.location.reload();
                    }
             });
         }
         else{
             alert("已中断上传文件！");
             window.location.reload();
         }
    }

     function submitFileName(){
         var _filename = $('#filename').val();
         var _file1 = $("#id-input-file-1").val();
         var division = new Array();
         division = _file1.split(".")
         var _file2 = $("#id-input-file-2").val();
         var _file3 = $("#id-input-file-3").val();
         if(_filename == "" || _filename == undefined || _filename == null){
             alert("尚未输入模型编码！");
         }
         else if(division[division.length-1] != "zip"){
             alert("请上传zip格式的工程文件！");
         }
         else if(_file2 == "" || _file2 == undefined || _file2 == null){
             alert("请选择配置文件！");
         }
         else if(_file3 == "" || _file3 == undefined || _file3 == null){
             alert("请选择参数文件！");
         }
         else{
             LoadingStart();
             var _url = '/Message';
             var formData = new FormData($('#saveFileToServer')[0]);
             formData.maxSize = 50000000000000;
             $.ajax({
                    url: _url,
                    type:'POST',
                    data:formData,
                    async:true,
                    cache:false,
                    contentType:false,
                    processData:false,
                    success:function(data){
                        LoadingEnd();
                        if(data == "是否覆盖原有文件夹"){
                            message();
                        }
                        else if(data == "文件上传成功"){
                            uploadFiles()
                //            alert("文件上传成功！");
               //             window.location.reload();
                        }
                    },
                    error:function(data){
                        LoadingEnd();
                        alert(data);
                        window.location.reload();
                    }
             });
         }
     }

     function LoadingStart()
     {
      $("#mask").show();
      $("#loading").show();
     }
     function LoadingEnd()
     {
      $("#mask").hide();
      $("#loading").hide();
     }

     function ShowDialogMessage(message)
     {
        var dialog = $( "#dialog-message" );
        dialog[0].children[0].innerText = message;
        dialog.removeClass('hide').dialog({
            modal: true,
        	title: "<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-check'></i> jQuery UI Dialog</h4></div>",
            title_html: true,
        	buttons: [
        	    {
        	        text: "OK",
        	        "class" : "btn btn-primary btn-xs",
        	        click: function() {
        				$( this ).dialog( "close" );
        			}
        		}
            ]
        });
     }

     function Reset(){
         document.getElementById("filename").value="";
       //  document.getElementById("saveFileToServer").reset();

     }

